package com.nd.rj.common.util.http;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.common.android.utils.http.SSLSocketFactoryEx;
import com.nd.rj.common.R;
import com.nd.rj.common.login.GlobalSetting;

public class HttpTool4Byte {
	private static final int TIMEOUT_MILLISEC = 60000;
	public static final int CONNECT_SUCCESS = 0;
	private static final String COOKIE = "Cookie";
	private static final String URL_OUT = "https://regapi.99.com/Packet/Default.ashx";
	private static final String URL_IN="http://testreg.99.com/Simple/Interface/Packet/Default.ashx";
	private Context mContext;

	public HttpTool4Byte(Context context) {
		mContext = context;
	}
	
	private String getUrl() {
		int env=GlobalSetting.getInstance(mContext).getNetworkEnv();
    	if (env == GlobalSetting.NETWORK_IN) {
    		return URL_IN;
    	} else if (env == GlobalSetting.NETWORK_OUT) {
    		return URL_OUT;
    	} else { 
    		return URL_OUT;
    	}
    }

	public int DoPost(byte[] param, StringBuffer receive,ArrayList<InputStream> data) {
		return DoPost(getUrl(), param, receive, data);
	}

	public int DoPost(String url, byte[] param, StringBuffer receive,ArrayList<InputStream> data) {
		int nRet = R.string.nd_unknow_error;
		InputStream inputStream = null;
		receive.delete(0, receive.length());
		try {
			// make a POST client
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClientParams.setRedirecting(httpParams, true);
			HttpClient client = getNewHttpClient(httpParams);
//			java.net.Proxy proxy = getProxy(mContext);
//			if (proxy != null) {
//				client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
//						proxy);
//			}
			HttpPost request = new HttpPost(url);
			ByteArrayEntity entity = new ByteArrayEntity(param);
			entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/x-www-form-urlencoded"));
			entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,
					HTTP.UTF_8));
			request.setEntity(entity);
			// POST and get response code
			HttpResponse response = client.execute(request);
			nRet = response.getStatusLine().getStatusCode();
			if (nRet==200){
				nRet=0;
			}
			// get response string
			inputStream = response.getEntity().getContent();
			data.add(inputStream);
//			byte[] b1=new byte[2];
//			inputStream.read(b1, 0, 2);
//			int code=EncryptTool.byteArrayToInt(b1);
//			byte[] b2=new byte[4];
//			inputStream.read(b2,0,4);
//			long timestamp=EncryptTool.byteArrayToLong(b2);
//			
//			BufferedInputStream bufferin = new BufferedInputStream(inputStream);
//			int n = 0;
//			byte b[] = new byte[20];
//			n = bufferin.read(b);
//			while (n != -1){
//				data.append(b, 0, n);
//				n = bufferin.read(b);
//			}
		} catch (SocketTimeoutException e) {
			nRet = R.string.nd_socket_timeout_error;
			receive.append(e.getMessage());
		} catch (SocketException e) {
			nRet = R.string.nd_socket_error;
			receive.append(e.getMessage());
		} catch (ConnectTimeoutException e) {
			nRet = R.string.nd_connect_timeout_error;
			receive.append(e.getMessage());
		} catch (UnknownHostException e) {
			nRet = R.string.nd_unknown_host_error;
			receive.append(e.getMessage());
		} catch (Exception e) {
			receive.append(e.getMessage());
		} finally {
//			if (inputStream != null) {
//				try {
//					inputStream.close();
//				} catch (IOException ioe) {
//				}
//			}
		}
		return nRet;
	}

	private java.net.Proxy getProxy(Context context) {
		if (needToProxy(context)) {
			Log.d("debug", android.net.Proxy.getDefaultHost());
			Log.d("debug", Integer.toString(android.net.Proxy.getDefaultPort()));
			return new java.net.Proxy(java.net.Proxy.Type.HTTP,
					new InetSocketAddress(android.net.Proxy.getDefaultHost(),
							android.net.Proxy.getDefaultPort()));
		}
		return null;
	}

	private static boolean needToProxy(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager == null) {
			return false;
		}

		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}
		String type = info.getTypeName();
		if (type.equalsIgnoreCase("MOBILE")) { // GPRS��ʽ

			String apnStr = info.getExtraInfo();
			if (apnStr != null) {
				apnStr = apnStr.toLowerCase();
				if (apnStr.contains("wap")) { // WAP��ʽ
					String proxyHost = android.net.Proxy.getDefaultHost();
					if (proxyHost != null && !proxyHost.equals("")) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
	private HttpClient getNewHttpClient(HttpParams params) {  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
            trustStore.load(null, null);  
            
            SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);  
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
    
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
    
            SchemeRegistry registry = new SchemeRegistry();  
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
            registry.register(new Scheme("https", sf, 443));  
    
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);  
    
            return new DefaultHttpClient(ccm, params);  
        } catch (Exception e) {  
            return new DefaultHttpClient();  
        }  
    }  
}
